//
//  WallpaperModifier.m
//  WeatherDesktop
//
//  Created by Justin Dell on 10/28/08.
//  Copyright 2008 . All rights reserved.
//

#import "WallpaperModifier.h"
#import "YahooWeatherData.h"
#import <unistd.h>

static NSString *testZip = @"99999";
static NSString *pictureFolder = @"/Users/Shared/WeatherDesktop/Pictures/";

@implementation WallpaperModifier

//@synthesize pictureFolder, zipCode, refreshRate;

/**
 *  Initializes a new instance of WallpaperModifier and starts the timer
 */
-(WallpaperModifier *)init {
    if ( self = [super init] ) {
        zipCode = @"61820";
    }
    return self;
}

/**
 *  Initializes a new instance of WallpaperModifier and starts the timer
 */
-(WallpaperModifier *)initWithZip:(NSString *)zip {
    if ( self = [super init] ) {
        zipCode = zip;
    }
    return self;    
}

/**
 *  Fetches weather and sets the desktop wallpaper, returns -1 on error
 */
-(NSInteger)setWallpaper:(id)object {
    NSDictionary *error = NULL;
    YahooWeatherData *yahooData = [[YahooWeatherData alloc] init];
    if ([yahooData fetchDataWithZip:zipCode] != 0) {
        NSLog(@"Error fetching data\n");
        NSString *theAlertMessage = @"Bad Internet Connection";
        NSRunAlertPanel( @"Error Fetching Data", theAlertMessage, @"OK", nil, nil );
        return -1;
    }
    NSString *pic = [yahooData getPicture];
    if ([pic compare:@""] == NSOrderedSame) {
        NSString *theAlertMessage = 
            @"The internet connection is fine, however there was an error fetching the weather. Are you sure your zip code is valid?";
        NSRunAlertPanel( @"Error Setting Picture", theAlertMessage, @"OK", nil, nil );
        return -1;
    }
    
    NSAppleEventDescriptor *retDescriptor = NULL;
    if ([zipCode compare:testZip] == NSOrderedSame) {
        retDescriptor = [NSAppleEventDescriptor nullDescriptor];
    }
    else {
        char cwd[128];
        memset(cwd, 0, 128);
        getcwd(cwd, 128);
        NSAppleScript *script = [[NSAppleScript alloc] initWithSource:[NSString
            stringWithFormat:@"\
                tell application \"Finder\"\n\
                set pFile to POSIX file \"%@%@\" as string\n\
                set desktop picture to file pFile\n\
                end tell", pictureFolder, pic]];
        retDescriptor = [script executeAndReturnError:&error];
        [script release];
    }

    if (retDescriptor == NULL) {
        NSString *theAlertMessage = 
            @"Fetch was successful, however there was an error setting the picture. Did you perhaps move the picture?";
        NSRunAlertPanel( @"Error Setting Picture", theAlertMessage, @"OK", nil, nil );
        return -1;
    }
    
    return 0;
}

/**
 * Sets the zip code
 */
-(void)setZipCode:(NSString *)zip {
    zipCode = zip;
}

/**
 * Returns the zip code
 */
-(NSString *)getZipCode {
    return zipCode;
}

@end
